const fs = require('fs')
const rimraf = require("rimraf")
const chalk = require('chalk')
const {
  exec
} = require('child_process')

module.exports = async (gitUrl, projectName) => {
  console.log(chalk.green(`开始创建项目:${projectName}`))
  const projectPath = `${process.cwd()}/${projectName}`
  const jsonFile= `${projectPath}/package.json`
  
  exec(`git clone ${gitUrl} ${projectName}`, async (error) => {
    if (error) {
      console.log(chalk.red('拷贝文件失败'))
      process.exit()
    }

    await rimraf(`${projectPath}/.git`,error=>{
      if (error) {
        process.exit()
      }
    });

    await fs.exists(jsonFile,(isExist)=>{
      isExist && fs.readFile(jsonFile, (err, data) => {
        if (error) {
          console.log(chalk.red('读取文件失败'))
          process.exit()
        }
        data = JSON.parse(data.toString())
        data.name = projectName
        fs.writeFile(jsonFile, JSON.stringify(data, "", "\t"), err => {
          if (err) {
            console.log(chalk.red('写入文件失败'))
            process.exit()
          }
          console.log(chalk.green('初始化完成,开始安装依赖...'))
        })
      })
    })

   await exec(`cd ${projectPath} && yarn install `, async (error) => {
      if (error) {
        process.exit()
      }
      console.log(chalk.green(`安装完成：To get Start: cd ${projectName} \n yarn serve`))
    })
  })
}